package com.taobao.rigel.rap.common.utils;
import com.taobao.rigel.rap.project.bo.Action;
import com.taobao.rigel.rap.project.bo.ObjectItem;
import net.sf.ehcache.Cache;
import net.sf.ehcache.CacheManager;
import net.sf.ehcache.Element;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.omg.PortableInterceptor.INACTIVE;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.io.IOException;

/**
 * Created by Bosn on 14/11/28.
 * Basic cache, need weight for string length.
 */
public class CacheUtils {
    private static final int DEFAULT_CACHE_EXPIRE_SECS = 600;
    private static final Logger logger = LogManager.getLogger(CacheUtils.class);

    public static final String KEY_MOCK_RULE = "KEY_MOCK_RULE:";
    public static final String KEY_MOCK_DATA = "KEY_MOCK_DATA";
    public static final String KEY_PROJECT_LIST = "KEY_PROJECT_LIST";
    public static final String KEY_CORP_LIST = "KEY_CORP_LIST";
    public static final String KEY_CORP_LIST_TOP_ITEMS = "KEY_CORP_LIST_TOP_ITEMS";
    public static final String KEY_WORKSPACE = "KEY_WORKSPACE";

    public static final String KEY_ACCESS_USER_TO_PROJECT = "KEY_ACCESS_USER_TO_PROJECT";
    public static final String KEY_NOTIFICATION = "KEY_NOTIFICATION";
    public static final String KEY_STATISTICS = "KEY_STATISTICS";
    public static final String KEY_STATISTICS_OF_TEAM = "KEY_STATISTICS_OF_TEAM";

//    private static JedisPool jedisPool;
//    private static Jedis jedis;

    private static final String KEY_DEFUALT= "KEY_DEFUALT";
    private static CacheManager manager;

    public CacheUtils() {}

    private static Cache getCache() {


        if(manager == null){
            manager = CacheManager.newInstance();
        }

        if (! manager.cacheExists(KEY_DEFUALT)) {
            manager.addCache(KEY_DEFUALT);
        }
        return manager.getCache(KEY_DEFUALT);
    }

    private static void returnJedis() {

    }

    /**
     * get cached Mock rule
     *
     * @param action
     * @param pattern
     * @return
     */
    public static String getRuleCache(Action action, String pattern, boolean isMockData) {
        int actionId = action.getId();
        String requestUrl = action.getRequestUrl();
        if (requestUrl == null) {
            requestUrl = "";
        }
        if (pattern.contains("noCache=true") || requestUrl.contains("{")
                || requestUrl.contains("noCache=true")) {
            return null;
        }
        String [] cacheKey = new String[]{isMockData ? KEY_MOCK_DATA
                 : KEY_MOCK_RULE, new Integer(actionId).toString()};
        return get(cacheKey);
    }

    /**
     * set Mock rule cache
     *
     * @param actionId
     * @param result
     */
    public static void setRuleCache(int actionId, String result, boolean isMockData) {
        String[] cacheKey = new String[]{isMockData ? KEY_MOCK_DATA : KEY_MOCK_RULE, new Integer(actionId).toString()};
        put(cacheKey, result);
    }

    public static void removeCacheByActionId(int id) {
        String[] cacheKey1 = new String[]{KEY_MOCK_RULE, new Integer(id).toString()};
        String[] cacheKey2 = new String[]{KEY_MOCK_DATA, new Integer(id).toString()};

        getCache().remove(StringUtils.join(cacheKey1, "|"));
        getCache().remove(StringUtils.join(cacheKey2, "|"));

    }


    public static void put(String [] keys, String value, int expireInSecs) {
        String cacheKey = StringUtils.join(keys, "|");

        getCache().put(new Element(cacheKey, value,Integer.MAX_VALUE,expireInSecs > 0 ? expireInSecs : Integer.MAX_VALUE));
    }

    public static void put(String [] keys, String value) {
        put(keys, value, DEFAULT_CACHE_EXPIRE_SECS);
    }

    public static String get(String []keys) {

        Element value =   getCache().get(StringUtils.join(keys, "|"));

        if(value == null || value.getObjectValue() == null) {
            return null;
        }

        return  String.valueOf(value.getObjectValue());
    }

    public static void del(String[] keys) {
        String cacheKey = StringUtils.join(keys, "|");
        getCache().remove(cacheKey);
        returnJedis();
    }

    public static void init() {
        getCache().flush();
        returnJedis();
    }
}
